#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: wang donghao
# Date  : 2020.11
# Email : dd.parkhere@gmail.com
###################################################################
import os
import subprocess
from dayu_widgets.message import MMessage
import ui
from dayu_widgets.qt import *
from config.launcher_envs import launch_env
import collections


class AnimeLauncher(ui.LauncherWin):

    def __init__(self, parent):
        super(AnimeLauncher, self).__init__(parent=parent)
        self.system_tool_list_view.item_clicked_sig.connect(self.launch)
        self.dcc_list_view.item_clicked_sig.connect(self.launch)
        self.custom_list_view.item_clicked_sig.connect(self.launch)
        self.add_custom_win = ui.AddCustomExe(self)
        self.add_custom_win.custom_soft_info_sig.connect(self.add_custom_soft)
        self.custom_pb.clicked.connect(self.add_custom_win.show)

        self.delete_custom_win = ui.DeleteCustomSoftWin(self)
        self.delete_pb.clicked.connect(self.delete_custom_win.show)
        self.delete_custom_win.to_delete_items_sig.connect(self.delete_custom_soft)

        self.q_settings = QSettings(u'ANIME_WOK_CONFIG', 'CustomSoft')
        self._arrange_buttons()

    def _arrange_buttons(self):
        self.system_tool_list_view.model().clear()
        self.dcc_list_view.model().clear()
        self.custom_list_view.model().clear()
        self.get_custom_soft()
        list_view_dict = {'DCC': self.dcc_list_view, 'Custom': self.custom_list_view, 'SYS': self.system_tool_list_view}
        od = collections.OrderedDict(sorted(launch_env.items(), key=lambda t: t[0]))
        for soft, _env in od.iteritems():
            the_list_view = list_view_dict.get(_env.get('GroupBox'))
            the_list_view.append_item(soft, _env.get('Icon'), _env.get('Display'))
        pass

    def launch(self, label):
        the_env = launch_env.get(label).get('Env')
        _env = self._edit_env(the_env)
        exe_str = launch_env.get(label).get('Exec')
        if 'python' not in exe_str and '--' not in exe_str and 'explorer' not in exe_str and not os.path.isfile(exe_str):
            return
        MMessage.config(5)
        MMessage.loading(u'正在开启%s, 请稍等...' % label,
                         parent=self)
        if launch_env.get(label).get('Type') == 'bat':
            subprocess.Popen(exe_str.encode(os.environ.get("SYSENCODING")), env=_env, shell=False)
        elif not launch_env.get(label).get('Type') == 'execfile':
            subprocess.Popen(exe_str.encode('utf-8'), env=_env, shell=True)
        else:
            # print exe_str
            execfile(exe_str)

    @staticmethod
    def _edit_env(env):
        _env = os.environ.copy()
        all_env = env
        if not all_env:
            final_env = {}
            for k, v in _env.iteritems():
                final_env.update({k: str(v)})
            return final_env
        for e in all_env:
            if e['mode'] == 'over':
                _env[e['name']] = str(e['value'])
            elif e['mode'] == 'pre':
                _env[e['name']] = str(e['value'] + ";" + os.environ.get(e['name'], ''))
            elif e['mode'] == 'post':
                _env[e['name']] = str(os.environ.get(e['name'], '') + ";" + e['value'])
            else:
                pass
        final_env = {}
        for k, v in _env.iteritems():
            final_env.update({k: str(v)})
        return final_env

    def add_custom_soft(self, soft_info):
        icon, exe, param = soft_info
        exe_label = exe.split('/')[-1].split('.')[0]
        self.q_settings.setValue(exe_label, '&&'.join(soft_info).encode('unicode_escape'))
        self._arrange_buttons()

    def get_custom_soft(self):
        all_custom_soft = self.q_settings.allKeys()
        self.delete_custom_win.add_rows(all_custom_soft)
        for label in all_custom_soft:
            soft_info = self.q_settings.value(label).decode('unicode_escape').split('&&')
            icon, exe, param = soft_info
            exe_label = exe.split('/')[-1].split('.')[0]
            launch_env.update({
                exe_label: {
                    "Env": "",
                    "Exec": exe,
                    "GroupBox": "Custom",
                    "Icon": icon
                },
            })

    def delete_custom_soft(self, soft_list):
        for soft in soft_list:
            self.q_settings.remove(soft)
            launch_env.pop(soft)
        self._arrange_buttons()





